package com.example.gymnasiumsystem.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

@WebFilter(filterName = "/IllegalFilter", urlPatterns = "/*/blog")  // 仅拦截 /blog/blog 路径的请求
public class IllegalFilter implements Filter {

    private List<String> illegalWords;

    /**
     * Default constructor.
     */
    public IllegalFilter() {
        // 默认构造函数
    }

    /**
     * @see Filter#destroy()
     */
    public void destroy() {
        // 销毁方法，暂时不需要实现
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    /**
     * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
     */
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)
            throws IOException, ServletException {
        // 获取请求的URL，检查是否是发表博客的请求
        HttpServletRequest httpRequest = (HttpServletRequest) req;
        String path = httpRequest.getRequestURI();
        ServletContext servletContext=((HttpServletRequest) req).getSession().getServletContext();
        // 如果是 /blog_publish 路径，执行敏感词过滤
        if (path.endsWith("/blog_publish")) {
            // 获取标题和内容参数
            String title = req.getParameter("title");
            String content = req.getParameter("content");
            // 进行敏感词检查
            if (title != null) {
                title = checkForIllegalWords(title,servletContext);
            }

            if (content != null) {
                content = checkForIllegalWords(content,servletContext);
            }

            // 将过滤后的标题和内容重新设置到请求中
            req.setAttribute("title", title);
            req.setAttribute("content", content);
        }

        // 继续传递请求
        chain.doFilter(req, resp);
    }

    private String checkForIllegalWords(String text,ServletContext servletContext) throws IOException {
        // 加载敏感词列表
        InputStream in = IllegalFilter.class.getResourceAsStream("/illegal.txt");
        InputStreamReader isr = new InputStreamReader(in);
        BufferedReader br = new BufferedReader(isr);
        illegalWords = new ArrayList<>();
        String str;

        while ((str = br.readLine()) != null) {
            illegalWords.add(str);
        }

        // 将敏感词列表存储到ServletContext中，以便全局使用
        servletContext.setAttribute("illegal_list", illegalWords);
        for (String word : illegalWords) {
            if (text != null && text.contains(word)) {
                // 使用 StringBuilder 替换敏感词
                StringBuilder replacement = new StringBuilder();
                for (int i = 0; i < word.length(); i++) {
                    replacement.append("*");
                }
                // 替换所有匹配
                text = text.replaceAll(word, replacement.toString());
            }
        }
        return text;
    }
}
